package com.adam.masterSpringMVC4.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyLoginSuccessHandler loginSuccessHandler;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.formLogin()
                .loginPage("/login")
//                .defaultSuccessUrl("/profile")
                .successHandler(loginSuccessHandler)
                .and()
                .logout().logoutSuccessUrl("/login").and()
                .authorizeRequests()
                .antMatchers("/webjars/**", "/login", "/oauth/github/callback")
                .permitAll()
                .anyRequest().authenticated();
        httpSecurity.addFilter(usernamePasswordAuthenticationFilter());
    }

    @Bean
    public UsernamePasswordAuthenticationFilter usernamePasswordAuthenticationFilter() throws Exception {
        UsernamePasswordAuthenticationFilter filter = new UsernamePasswordAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(loginSuccessHandler);
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }

}
